package java44th.group.bean.typehandle;

import com.fasterxml.jackson.databind.ObjectMapper;
import java44th.group.bean.common.BaseStringUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @Aurhor: 帅的一批
 * @CreateAt: 2022/10/13 11:38
 * @Description:
 * @PACKAGE_NAME： java44th.group.bean.typehandle
 */

@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandle implements TypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(parameter);
        ps.setString(i,value);
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String hobbys = cs.getString(columnIndex);
        return transferIntegerToSntegerArray(hobbys);
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        return transferIntegerToSntegerArray(rs.getString(columnIndex));

    }

    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        return transferIntegerToSntegerArray(rs.getString(columnName));
    }


    @SneakyThrows
    private Integer[] transferIntegerToSntegerArray(String result) {
        if (!BaseStringUtils.isEmpty(result)) {
            Integer[] integers = objectMapper.readValue(result, Integer[].class);
            return integers;
        }
        return new Integer[0];
    }
}
